package com.dsg.utils;

import com.dsg.entity.Staff;
import com.dsg.service.StaffService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component("dbRealm")
public class DbRealm extends AuthorizingRealm {

    @Resource
    private StaffService staffService;


    @Resource
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Staff staff = (Staff) principalCollection.getPrimaryPrincipal();
        List<String> list= (List<String>) staffService.login(staff.getLoginId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(list);
        return info;
    }


    /**
     * 后台登录认证过程
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String LoginId = token.getPrincipal().toString();
        Staff staff = staffService.login(LoginId);
        if(staff==null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(staff,staff.getPassword(), ByteSource.Util.bytes(staff.getSalt()),super.getName());
        return info;
    }
}
